import Vue from 'vue'
import { getToken } from '@/utils/storage'
import { Toast } from 'vant'
import VueRouter from 'vue-router'
const Register = () => import('@/views/one/Register.vue')
const Login = () => import('@/views/one/Login.vue')
const Detail = () => import('@/views/one/Detail.vue')
const Layout = () => import('@/views/one/Layout.vue')
const Article = () => import('@/views/tow/Article.vue')
const Collect = () => import('@/views/tow/Collect.vue')
const Like = () => import('@/views/tow/Like.vue')
const User = () => import('@/views/tow/User.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  { path: '/register', component: Register },
  { path: '/login', component: Login },
  { path: '/detail/:id', component: Detail },
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  }
]

const router = new VueRouter({
  routes
})

const whiteList = ['/register', '/login']
// 导航守卫 =>全局前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机:每次页面跳转都会触发该函数
  // 只要注册了全局前置守卫，路由会立即瘫痪，必须要调用 next() 方法来放行
  // 参数1: to 到哪里去
  // 参数2: from 从哪里来
  // 参数3: next 函数，决定是否放行，next() 表示放行，next(路径') 表示强制跳转到指定路由，next(false)·表示不放行
  const token = getToken()
  if (token) {
    next()
  } else if (whiteList.includes(to.path)) {
    next()
  } else {
    Toast.fail('您还没有登录，请去登录')
    next('/login')
  }
})

export default router
